// Created by liusc on 2020/8/5-9:24.
import { getDict } from "~/utils";
import uploadMedia from "@/components/upload-media";
import {
    getItem2,
    getObj,
    putObj3,
} from "@/views/wy-budget/api/budgetaddapply.js";
import {
    getFiles,
    checkFiles,
    delFiles
} from "@/views/wy-budget/api/fileoperation.js";
import Budget from '@/assets/vue-mixin/budget'

export default {
    name: "addapply_edit",
    mixins: [Budget],
    components: {
        uploadMedia
    },

    data() {
        var doubleValidate = (rule, value, callback) => {
            // let reg = /^[0-9]+(.[0-9]{1,2})?$/;
            let reg = /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/;
            let lable = rule.message;
            if (!reg.test(value)) {
                return callback(new Error("数值格式错误"));
            } else {
                callback();
            }
        };

        return {
            isShow: false,
            fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
            uploadFileList: [],
            fileList: [],
            modelType: "budgetApply",
            isEdit: true,
            busId: "",

            form: {
                applyData: {
                    applyId: "",
                    budgetId: "",
                    budgetCode: "",
                    applyName: "",
                    applyDept: "",
                    applyType: "",
                    budgetSum: "",
                    budgetSum2: "",
                    changeAmount: "",
                    remarks: "",
                    fileId: ""
                },
                itemValueList: [],
                operateType: ""
            },

            rules: {
                applyData: {
                    budgetSum: [
                        {
                            required: true,
                            message: "请输入预算总金额",
                            trigger: "blur"
                        },
                        {
                            validator: doubleValidate,
                            trigger: "blur"
                        }
                    ],
                    budgetSum2: [
                        {
                            required: true,
                            message: "调整后金额不能为空",
                            trigger: "blur"
                        },
                        {
                            validator: doubleValidate,
                            trigger: "blur"
                        }
                    ],
                    changeAmount: [
                        {
                            required: true,
                            message: "变化金额不能为空",
                            trigger: "blur"
                        },
                        {
                            validator: doubleValidate,
                            trigger: "blur"
                        }
                    ],
                    remarks: [
                        {
                            required: true,
                            message: "请输入费用说明",
                            trigger: "blur"
                        },
                        {
                            min: 0,
                            max: 100,
                            message: "长度在 0 到 100 个字符",
                            trigger: "blur"
                        }
                    ]
                }
            }
        };
    },

    computed: {
        applyDept2: function () {
            let types = getDict("budget_department");
            let pv = this.form.applyData.applyDept;
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv);
                return pts ? pts[0].label : "";
            }
            return "";
        },

        applyType2: function () {
            let types = getDict("budget_type");
            let pv = this.form.applyData.applyType;
            if (pv && types.length > 0) {
                const pts = types.filter(t => t.value == pv);
                return pts ? pts[0].label : "";
            }
            return "";
        }
    },

    mounted() { },

    created() {
        const loading = this.$loading({
            lock: true,
            text: "数据加载中"
        });

        setTimeout(() => {
            getObj(this.$route.params.applyId)
                .then(respData => {
                    this.$refs["add-form"].resetFields();
                    this.form.applyData = respData.data.data;
                    this.initItem(this.form.applyData.applyId);

                    this.busId = this.form.applyData.fileId;
                    this.$refs.myApply.getFiles(this.busId);

                    loading.close();
                })
                .catch(e => {
                    loading.close();
                    this.$message({
                        type: "error",
                        message: "数据获取失败!"
                    });
                });
        }, 200);
    },
    methods: {
        // 科目
        initItem() {
            getItem2(this.form.applyData.applyId).then(rep => {
                let rspD = rep.data.data;

                if (rspD) {
                    rspD = rspD.map((rs, index) => {
                        // if(rs.isLeaf)
                        // rs['sortNum'] = index + 1
                        return rs;
                    });
                }
                this.form.itemValueList = rspD;
            });
        },

        // 取消
        cancel() {
            this.closeNowRouter();
        },

        // 保存
        commit() {
            this.form.operateType = "3";
            this.checkWillBe() && this.$refs["add-form"].validate(valid => {
                if (valid) {
                    if (this.uploadFileList.length > 0) {
                        if (!this.isEdit) {
                            this.$refs.myApply.submit(
                                this.modelType,
                                this.busId
                            );
                        } else {
                            this.$refs.myApply.submit(this.modelType, null);
                        }
                    } else {
                        getFiles(this.busId, this.modelType).then(rep => {
                            this.fileList = rep.data.data;
                            if (this.fileList && this.fileList.length > 0) {
                                this.sendFormData();
                            } else {
                                this.$alert("请上传附件");
                                return;
                            }
                        });
                    }
                }
            });
        },


        // 提交
        commit2() {
            this.form.operateType = "4";
            if (this.checkWillBe() === '') {
                this.$refs["add-form"].validate(valid => {
                    if (valid) {
                        // this.sendFormData();
                        if (this.uploadFileList.length > 0) {
                            if (!this.isEdit) {
                                this.$refs.applyEdit.submit(
                                    this.modelType,
                                    this.busId
                                );
                            } else {
                                this.$refs.applyEdit.submit(this.modelType, null);
                            }
                        } else {
                            getFiles(this.busId, this.modelType).then(rep => {
                                this.fileList = rep.data.data;
                                if (this.fileList && this.fileList.length > 0) {
                                    this.sendFormData();
                                } else {
                                    this.$alert("请上传附件");
                                    return;
                                }
                            });
                        }
                    }
                });
            } else {
                this.$message({
                    message: `${this.checkWillBe()}   科目调整后金额为为空，请输入完整调整后金额`,
                    type: "warning"
                });
            }
        },
        sendFormData(val) {
            //this.loadAction("请稍等...");

            if (val && this.isEdit) {
                this.form.applyData.fileId = val;
                this.busId = val;
            }

            if (this.isEdit) {
                putObj3(this.form)
                    .then(rep => {
                        this.success_message("保存成功");
                        //this.loadClose();
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        this.errormessage("保存失败");
                        //this.loadClose();
                    });
            } else {
                putObj3(this.form)
                    .then(rep => {
                        this.success_message("修改成功");
                        //this.loadClose();
                        this.closeNowRouter();
                    })
                    .catch(e => {
                        this.errormessage("修改失败");
                        //this.loadClose();
                    });
            }
        },

        success_message(msg) {
            this.$message({
                type: "success",
                message: msg
            });
        },
        errormessage(msg) {
            this.$message({
                type: "error",
                message: msg
            });
        },

        closeNowRouter() {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            //跳转
            this.$router.push({
                name: "addapply_list"
            });
        },

        onSuccess(rep, file, fileList) {
            //文件上传成功，开始保存表单
            //this.loadClose();
            if (rep.data != null) {
                this.sendFormData(rep.data);
            } else {
                this.err("提交失败");
            }
        },

        onError(err, file, fileList) {
            //this.loadClose();
            this.err("提交失败");
        },

        beforeUpload() {
            //this.loadAction("请稍等...");
        },

        // 删除文件
        handleClean(file) {
            this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    delFiles(file.fileId, this.modelType).then(resp => {
                        if (resp.data.code === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!"
                            });
                            //this.fileList = []
                            this.fileList = this.fileList.filter(
                                file => file.fileId != fileId
                            );
                        } else {
                            this.$message({
                                type: "error",
                                message: "删除失败!"
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除"
                    });
                });
        }
    }
};
